﻿using Microsoft.EntityFrameworkCore;
using MyECommerceProject.Interfaces;
using MyECommerceProject.Models;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace MyECommerceProject.Data
{
    public class ProductRepository : IProductRepository
    {
        private readonly MyDbContext _context;

        public ProductRepository(MyDbContext context)
        {
            _context = context;
        }

        public async Task<IEnumerable<Product>> GetProductsAsync()
        {
            var result= await _context.Products.ToListAsync();

            return result;
        }

        public async Task<Product> GetProductByIdAsync(int productId)
        {
            return await _context.Products.FindAsync(productId);
        }

        public async Task AddProductAsync(Product product)
        {
            await _context.Products.AddAsync(product);
            await _context.SaveChangesAsync();
        }

        public async Task UpdateProductAsync(Product product)
        {
            _context.Products.Update(product);
            await _context.SaveChangesAsync();
        }

        public async Task DeleteProductAsync(int productId)
        {
            var product = await _context.Products.FindAsync(productId);
            if (product != null)
            {
                _context.Products.Remove(product);
                await _context.SaveChangesAsync();
            }
        }

        public async Task<IEnumerable<Product>> GetProductsAsyncByOptionAsync(ProductSearchOption option)
        {

            var query = _context.Products.AsQueryable();

            if (option == null)
            {
                return await GetProductsAsync();
            }

            if(option.minPrice.HasValue)
            {
                query = query.Where(p => p.Price >= option.minPrice);
            }

            if (option.maxPrice.HasValue)
            {
                query = query.Where(p => p.Price <= option.maxPrice);
            }

            if (!string.IsNullOrEmpty(option.Category))
            {
                query = query.Where(p => p.Category == option.Category);
            }

            return await query.ToListAsync();
            
        }
    }
}